import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyBgPage.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyPage.dart';

import 'CommentTeacher.dart';
import 'RecordList.dart';
import 'ReviewClass.dart';

class ReviewList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ReviewList();
  }
}

class _ReviewList extends State<ReviewList> {
  DateTime? startTime;
  DateTime? endTime;

  ChooseStartTime() {
    DatePicker.showDatePicker(context,
        dateFormat: "yyyy年 MM月 dd日 HH時 mm分", //通过空格设置滚轮数量
        initialDateTime: startTime,
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      if (endTime != null && dateTime.isAfter(endTime!)) {
        showToast("開始時間必須早於結束時間");
        return;
      }
      startTime = dateTime;
      chooseClass = null;
      setState(() {});
      getClass();
    });
  }

  ChooseEndTime() {
    DatePicker.showDatePicker(context,
        dateFormat: "yyyy年 MM月 dd日 HH時 mm分", //通过空格设置滚轮数量
        initialDateTime: endTime,
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      if (startTime != null && dateTime.isBefore(startTime!)) {
        showToast("開始時間必須早於結束時間");
        return;
      }
      endTime = dateTime;
      chooseClass = null;
      setState(() {});
      getClass();
    });
  }

  dynamic chooseClass;
  List<dynamic> classList = [];

  ChooseClass() {
    if (startTime == null || endTime == null) {
      showToast("需要先選擇開始與結束日期");
      return;
    }
    showWheelDialog2(context, "", classList, "lessonName", (int index) {
      chooseClass = classList[index];
      setState(() {});
      getUserClass(chooseClass["lessonId"].toString());
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getUserClass("");
      getCommentWord();
      getClass();
    });
    super.initState();
  }

  ///下拉清單
  getClass() {
    if (startTime == null || endTime == null) {
      return;
    }
    SmartDialog.showLoading();
    HttpGo(context).post("/Material/GetReviewMaterialLesson", {
      "studentId": Global.studentId,
      "beginDateTime": getUtcTime(startTime!),
      "endDateTime": getUtcTime(endTime!),
    }, (data) {
      SmartDialog.dismiss();
      classList = data["lessonList"];
    }, (code, error) {
      SmartDialog.dismiss();
      showToast(error);
    });
  }

  /// 列表
  List<dynamic> userClassList = [];

  getUserClass(String lessonId) {
    Map<String, dynamic> params = {"studentId": Global.studentId};
    if (startTime != null) {
      params["beginDateTime"] = getUtcTime(startTime!);
    }
    if (endTime != null) {
      params["endDateTime"] = getUtcTime(endTime!);
    }
    if (lessonId.isNotEmpty) {
      params["lessonId"] = lessonId;
    }
    HttpGo(context).post("/Material/GetReviewMaterialClassroom/", params, (data) {
      userClassList = data["lessonList"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  ///評價快捷詞語
  getCommentWord() {
    HttpGo(context).get("/HiNote/GetCommnetDefault", {}, (data) {
      Global.commentWords = data["description"];
    }, (code, error) => showToast(error), showLoading: false);
  }

  @override
  Widget build(BuildContext context) {
    return MyBgPage(
        "",
        Container(
            child: Column(
          children: [
            Padding(
                padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
                child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  Text("選擇開始與結束日期", style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: MyColor.Green)),
                  Padding(
                      padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
                      child: Row(children: [
                        Expanded(child: ChooserBox(getStrTime(startTime), bgColor: MyColor.White, onTap: ChooseStartTime)),
                        Text("　~　"),
                        Expanded(child: ChooserBox(getStrTime(endTime), bgColor: MyColor.White, onTap: ChooseEndTime)),
                      ])),
                  Text("選擇課程", style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: MyColor.Green)),
                  ChooserBox(chooseClass == null ? "" : chooseClass["lessonName"],
                      bgColor: MyColor.White, margin: EdgeInsets.fromLTRB(0, 8, 0, 8), onTap: ChooseClass),
                ])),
            Expanded(
                child: ListView.builder(
                    itemCount: userClassList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return ItemClass(userClassList[index]);
                    }))
          ],
        )),
        bgColor: MyColor.F3);
  }
}

class ItemClass extends StatefulWidget {
  dynamic classData;

  ItemClass(this.classData);

  @override
  State<StatefulWidget> createState() {
    return _ItemClass();
  }
}

class _ItemClass extends State<ItemClass> {
  ///評價
  comment() {
    showWidgetDialog(
        context,
        CommentTeacher(
          lessonId: widget.classData["lessonId"],
          classroomId: widget.classData["classroomId"],
          commentWords: Global.commentWords,
          commentCallback: () {
            widget.classData["isComment"] = true;
            setState(() {});
          },
        ));
  }

  ///教師註記
  teacherNote() {
    PageUtil().open(context, ReviewClass(widget.classData));
  }

  ///上課錄影
  classRecord() {
    List<dynamic> classedUrls = widget.classData["classedUrl"];
    if (classedUrls.length < 1) {
      showToast("暫無上課錄影");
      return;
    }
    PageUtil().open(context, RecordList(classedUrls));
  }

  @override
  Widget build(BuildContext context) {
    String beginTime = getStrTime(getTimeByUtc(widget.classData["beginTime"]), DateUtil.YMDHM);
    String endTime = getStrTime(getTimeByUtc(widget.classData["endTime"]), DateUtil.HM);
    String className = widget.classData["lessonName"].toString();
    if (className.length > 10) {
      className = className.substring(0, 10) + "...";
    }
    return GestureDetector(
        onTap: () {
          PageUtil().open(context, ReviewClass(widget.classData));
        },
        child: Container(
            color: MyColor.White,
            margin: EdgeInsets.only(bottom: 8),
            child: Column(children: [
              Padding(
                  padding: EdgeInsets.all(12),
                  child: Row(children: [
                    Container(
                        decoration: Global.getBg(MyColor.F3, 24),
                        child: NetImage(widget.classData["teacherPhoto"], width: 32, height: 32, radius: 16, padding: EdgeInsets.all(4))),
                    Container(width: 16),
                    Expanded(
                        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      Row(children: [
                        Text("${widget.classData["teacherName"]}",
                            style: TextStyle(fontSize: 14, color: Color(0xffff8484), fontWeight: FontWeight.bold)),
                        Container(width: 8),
                        widget.classData["teacherWebcam"] ? Container() : LocalImage("video-off.png", width: 20)
                      ]),
                      Button("${widget.classData["plateformShortName"]}",
                          height: 20, width: 20, bgColor: MyColor.C5, radius: 20, fontSize: 11, margin: EdgeInsets.only(top: 4))
                    ])),
                    Text("$className\n$beginTime - $endTime",
                        textAlign: TextAlign.end, style: TextStyle(fontSize: 13, height: 2, color: Color(0xff005eab)))
                  ])),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Visibility(
                    visible: !widget.classData["isComment"],
                    child: Expanded(child: IconBtn(name: '評價', image: 'evaluate.png', onTap: comment)),
                  ),
                  Expanded(child: IconBtn(name: '教師註記', image: 'marker.png', onTap: teacherNote)),
                  Expanded(child: IconBtn(name: '上課錄影', image: 'video-camera.png', onTap: classRecord)),
                ],
              )
            ])));
  }
}

class IconBtn extends StatelessWidget {
  String image;
  String name;
  Function() onTap;

  IconBtn({required this.image, required this.name, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: onTap,
        behavior: HitTestBehavior.opaque,
        child: Container(
            padding: EdgeInsets.symmetric(vertical: 4),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [LocalImage(image, height: 24, width: 32), Text(name, style: TextStyle(fontSize: 13, color: MyColor.Green))])));
  }
}
